from app import app
from flask import Flask, render_template, request, jsonify, make_response, session
from flask_restful import inputs
from app.libs.Codes import TextCode
from app.libs.Verifys import passWord
from app.models import *
from app.admin.admin_login import admin_require
from app.libs.QINIU import delect as QiniuDel, pfop_m3u8
from sqlalchemy import or_
import time
import hashlib
import random
from app.setting import *
from html import unescape
import re
from sqlalchemy.orm.attributes import flag_modified


# 后台分配用户表
@app.route('/pdd/admin/allot/user/list', methods=["get"])
@admin_require
def admin_allot_user_list(aid):

    if not aid.job.allot:
        return jsonify(code=-103, msg="你无权访问，需要管理员授权")
    '''
    :param page:页码
    :param keyword:搜索关键词
    :param status:状态
    :param zone:空间 1：首页 2：个人中心 3：功能页
    :return:
    '''
    page = request.args.get('page', default=0, type=int)
    keyword = request.args.get("keyword", type=str)
    call_status = request.args.get("call_status", type=int)
    wechat_status = request.args.get("wechat_status", type=int)
    Intent_status = request.args.get("Intent_status", type=int)
    allot_status = request.args.get("allot_status", type=inputs.boolean)
    startTime = request.args.get("startTime", type=str)
    endTime = request.args.get("endTime", type=str)
    pageSize = request.args.get('pageSize', default=10, type=int)


    sql = list()
    if keyword:
        sql.append(or_(User.phone.like(f"%{keyword}%"), UserSell.wechat.like(f"%{keyword}%")))
    if startTime and endTime:
        endTime = datetime.datetime.strptime(endTime, '%Y-%m-%d') + datetime.timedelta(days=1)
        sql.append(User.createtime.between(startTime, endTime))
    if allot_status is not None:
        if allot_status:
            sql.append(User.aid != None)
        else:
            sql.append(User.aid == None)


    if call_status is not None:
        sql.append(UserSell.call_status == call_status)
    if wechat_status is not None:
        sql.append(UserSell.wechat_status == call_status)
    if Intent_status is not None:
        sql.append(UserSell.Intent_status == Intent_status)

    pager = User.query.join(UserSell).filter(*sql).paginate(page, per_page=pageSize, error_out=False)

    data = []
    for i in pager.items:
        data.append({
            "id": i.id,
            "phone": i.phone,
            "keyword": i.sell.keyword,
            "call_status": i.sell.call_status,
            "wechat_status": i.sell.wechat_status,
            "Intent_status": i.sell.Intent_status,
            "createtime": str(i.createtime),
            "source": i.sell.source,
            "name": "未分配" if i.admin is None else i.admin.name
        })
    return jsonify(code=0, msg="成功",
                   page=pager.page,
                   total=pager.total,
                   pages=pager.pages,
                   rows=data,
                   )


# 销售列表
@app.route('/pdd/admin/sell', methods=["get"])
@admin_require
def admin_sell(aid):
    admin = Admin.query.join(Admin_job).filter(Admin_job.sell).all()
    data = []
    for i in admin:
        sumCount = db.session.query(db.func.count(User.id).label("count")).filter(User.aid == i.id).first()
        surplus = db.session.query(db.func.count(User.id).label("count")).join(UserSell).filter(User.aid == i.id,
                                                                                                UserSell.call_status == 0).first()

        wechat = db.session.query(db.func.count(User.id).label("count")).join(UserSell).filter(User.aid == i.id,
                                                                                                UserSell.wechat_status == 0).first()

        data.append({
            "aid": i.id,
            "username": i.username,
            "name": i.name,
            "sumCont": sumCount.count,
            "surplus":surplus.count,
            "wechatCount":wechat.count
        })
    return jsonify(code=0, msg="获取成功", data=data)


# 后台销售分配
@app.route('/pdd/admin/allot/user', methods=["post"])
@admin_require
def admin_allot_user(aid):

    if not aid.job.allot:
        return jsonify(code=-103, msg="无权操作，需要管理员授权")

    '''
    :param page:页码
    :param keyword:搜索关键词
    :param status:状态
    :param zone:空间 1：首页 2：个人中心 3：功能页
    :return:
    '''
    data = request.json
    admin_id = data.get("aid")
    userlist = data.get("userlist")

    if userlist is None:
        return jsonify(code=-1, msg="请选中要分配的用户")
    if admin_id is None:
        return jsonify(code=-1, msg="请选择要分配谁？")
    admin = Admin.query.join(Admin_job).filter(Admin.id == admin_id, Admin_job.sell).first()
    if not admin:
        return jsonify(code=-1, msg="未找到该销售信息，请刷新重试～")




    User.query.filter(User.id.in_(userlist)).update({"aid": admin.id}, synchronize_session=False)

    operate_comment = []
    operate_comment.append({"name": "姓名", "content": admin.name})
    operate_comment.append({"name": "分配数量", "content": len(userlist)})
    log = Admin_operate_log(func=admin.username + "的资源", up=1, comment=operate_comment, aid=aid.id)
    try:
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="分配成功")
    except:
        db.session.rollback(code=-1, msg="分配失败")

# 后台资源回滚
@app.route('/pdd/admin/allot/rollback', methods=["post"])
@admin_require
def admin_allot_rollback(aid):

    if not aid.job.allot:
        return jsonify(code=-103,msg="无权操作，需要管理员授权")

    data = request.json
    userlist = data.get("userlist")
    wechat_status = data.get("wechat_status")
    call_status = data.get("call_status")
    Intent_status = data.get("Intent_status")
    comment_del = data.get("comment_del")
    if userlist is None and type(userlist) != list:
        return jsonify(code=-1, msg="请选中要回滚的用户")

    if wechat_status is None and wechat_status not in [True,False]:
        return jsonify(code=-1, msg="请选中要回滚的微信状态")
    if call_status is None and call_status not in [True,False]:
        return jsonify(code=-1, msg="请选中要回滚的拨号状态")
    if Intent_status is None and Intent_status not in [True,False]:
        return jsonify(code=-1, msg="请选中要回滚的意向状态")
    if comment_del is None and comment_del not in [True,False]:
        return jsonify(code=-1, msg="请选择是否清空备注")

    user = User.query.filter(User.id.in_(userlist)).all()

    try:
        for i in user:
            i.aid = None

            if wechat_status:
                i.sell.wechat_status = 0
            if call_status:
                i.sell.call_status = 0
            if Intent_status:
                i.sell.Intent_status = 0

            if comment_del:
                UserComment.query.filter(UserComment.uid==i.id).delete(synchronize_session=False)

        db.session.commit()
        return jsonify(code=0, msg="回滚成功")
    except:
        db.session.rollback(code=-1, msg="回滚失败")




'''
销售用户信息操作

'''


# 后台销售资源信息表
@app.route('/pdd/admin/sell/user', methods=["get"])
@admin_require
def admin_sell_user(aid):
    '''
    :param page:页码
    :param keyword:搜索关键词
    :param status:状态
    :param zone:空间 1：首页 2：个人中心 3：功能页
    :return:
    '''

    page = request.args.get('page', default=0, type=int)
    keyword = request.args.get("keyword", type=str)
    call_status = request.args.get("call_status", type=int)
    wechat_status = request.args.get("wechat_status", type=int)
    Intent_status = request.args.get("Intent_status", type=int)
    startTime = request.args.get("startTime", type=str)
    endTime = request.args.get("endTime", type=str)
    pageSize = request.args.get('pageSize', default=10, type=int)

    sql = list()
    if keyword:
        sql.append(or_(User.phone.like(f"%{keyword}%"), UserSell.wechat.like(f"%{keyword}%")))
    if startTime and endTime:
        endTime = datetime.datetime.strptime(endTime, '%Y-%m-%d') + datetime.timedelta(days=1)
        sql.append(User.createtime.between(startTime, endTime))

    if call_status is not None:
        sql.append(UserSell.call_status == call_status)
    if wechat_status is not None:
        sql.append(UserSell.wechat_status == call_status)
    if Intent_status is not None:
        sql.append(UserSell.Intent_status == Intent_status)

    pager = User.query.join(UserSell).filter(*sql).filter(User.aid == aid.id).paginate(page, per_page=pageSize,
                                                                                       error_out=False)

    data = []
    for i in pager.items:
        data.append({
            "id": i.id,
            "phone": i.phone,
            "keyword": i.sell.keyword,
            "wechat":i.sell.wechat,
            "call_status": i.sell.call_status,
            "wechat_status": i.sell.wechat_status,
            "Intent_status": i.sell.Intent_status,
            "createtime": str(i.createtime),
            "source": i.sell.source,
            "userPhoto": i.userPhoto,
            "userLevel":{
                "name":"普通会员",
                "color":"rgba(255,255,255,1)",
                "background":"rgba(119,119,119,1)"
            }
        })
    return jsonify(code=0, msg="成功",
                   page=pager.page,
                   total=pager.total,
                   pages=pager.pages,
                   rows=data,
                   )


# 销售保存用户信息
@app.route('/pdd/admin/sell/user/edit', methods=["post"])
@admin_require
def admin_sell_user_edit(aid):
    id = request.form.get("id",type=int)
    wechat = request.form.get("wechat",type=str)
    wechat_status = request.form.get("wechat_status",type=int)
    call_status = request.form.get("call_status",type=int)
    Intent_status = request.form.get("Intent_status", type=int)

    if id is None:
        return jsonify(code=-1, msg="请求出错，刷新页面重试～")

    user = User.query.filter(User.id==id,User.aid==aid.id).first()
    if not user:
        return jsonify(code=-1, msg="未找到该用户信息，请刷新重试～")


    if wechat is not None:
        user.sell.wechat = wechat

    wechat_status_day = None
    call_status_day = None
    Intent_status_day = None

    if wechat_status in [0,1,2] and user.sell.wechat_status != 0:
        user.sell.wechat_status = wechat_status
        wechat_status_day = wechat_status
    if call_status in [0,1,2,3] and user.sell.call_status != call_status:
        user.sell.call_status = call_status
        call_status_day = call_status

    if Intent_status in [0,1,2,3] and user.sell.Intent_status != Intent_status:
        user.sell.Intent_status = Intent_status
        Intent_status_day = Intent_status
    if wechat_status_day or call_status_day or Intent_status_day:
        day = SellDays.query.filter(SellDays.uid==user.id,SellDays.aid==aid.id,
                                    db.cast(SellDays.createtime, db.DATE) == datetime.datetime.now().date()).first()
        if day:
            if call_status_day:
                day.call_status = call_status_day
            if wechat_status_day:
                day.wechat_status = wechat_status_day
            if Intent_status_day:
                day.Intent_status = Intent_status_day

        else:
            sdayobj = SellDays(uid=user.id,aid=aid.id,call_status=call_status_day,wechat_status=wechat_status_day,Intent_status=Intent_status_day)
            db.session.add(sdayobj)

    try:

        db.session.commit()
        return jsonify(code=0, msg="保存信息成功")
    except:
        db.session.rollback(code=-1, msg="保存信息失败")

# 销售新增备注信息
@app.route('/pdd/admin/sell/user/commnet/add', methods=["post"])
@admin_require
def admin_sell_user_commnet_add(aid):
    id = request.form.get("id",type=int)
    content = request.form.get("content",type=str)

    if id is None:
        return jsonify(code=-1, msg="请求出错，刷新页面重试～",data={
        "id":None,
        "name":aid.name,
        "content":"请求出错，刷新页面重试～",
        "Photo":aid.userPhoto,
        "createtime":datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    })
    if content is None:
        return jsonify(code=-1, msg="请求出错，不能备注空内容",
                       data={
                           "id": None,
                           "name": aid.name,
                           "content": "请求出错，不能备注空内容～",
                           "Photo": aid.userPhoto,
                           "createtime": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                       }
                       )

    user = User.query.filter(User.id==id,User.aid==aid.id).first()
    if not user:
        return jsonify(code=-1, msg="未找到该用户信息，请刷新重试～",data={
        "id":None,
        "name":aid.name,
        "content":"未找到该用户信息，请刷新重试～",
        "Photo":aid.userPhoto,
        "createtime":datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    })
    ucomment = UserComment(uid=user.id,aid=aid.id,content=content)

    try:
        db.session.add(ucomment)
        db.session.commit()
        return jsonify(code=0, msg="备注成功",data={
        "id":ucomment.id,
        "name":ucomment.admin.name,
        "content":ucomment.content,
        "Photo":ucomment.admin.userPhoto,
        "createtime":str(ucomment.createtime)
    })
    except:
        db.session.rollback(code=-1, msg="备注失败")

# 销售获取备注信息
@app.route('/pdd/admin/sell/user/commnet', methods=["get"])
@admin_require
def admin_sell_user_commnet(aid):
    id = request.args.get("id",type=int)
    minId = request.args.get("minId",type=int)


    user = User.query.filter(User.id==id,User.aid==aid.id).first()
    if not user:
        return jsonify(code=-1, msg="未找到该用户信息，请刷新重试～")
    sql = list()
    if minId is not None:
        sql.append(UserComment.id < minId)

    ret = UserComment.query.filter(*sql).order_by(UserComment.createtime.desc()).limit(10).all()

    data = [{
        "id":i.id,
        "name":i.admin.name,
        "content":i.content,
        "Photo":i.admin.userPhoto,
        "createtime":str(i.createtime)
    }for i in ret[::-1]]

    return jsonify(code=0,msg="获取成功",data=data,minId=ret[-1].id if ret else False)

# 添加合作
@app.route('/pdd/admin/usercoop/add', methods=["post"])
@admin_require
def admin_user_coop_add(aid):

    '''

    :param phone 合作手机号
    :param name 合作用户姓名
    :param wechat 合作用户微信号
    :param shopName 合作用户店铺名
    :param coopName 合作套餐名
    :param price = 收款
    :param startTime 开始时间
    :param endTime 结束时间
    :param comment 备注
    :param payType 0:支付宝支付 2：微信支付 3：银行转账 4：其他方式
    :param payorder 支付交易流水号
    :return:
    '''


    phone = request.form.get("phone",type=int)
    name = request.form.get("name",type=str)
    wechat = request.form.get("wechat", type=str)
    shopName = request.form.get("shopName", type=str)
    coopName = request.form.get("coopName", type=str)
    price = request.form.get("price",type=float)
    payType = request.form.get("payType",type=int)
    payorder = request.form.get("payorder",type=str)
    startTime = request.form.get("startTime",type=str)
    endTime = request.form.get("endTime",type=str)
    comment = request.form.get("comment",type=str)

    if phone is None:
        return jsonify(code=-1, msg="请求出错，刷新页面重试～")
    if coopName is None:
        return jsonify(code=-1, msg="请填写合作名称～")
    if shopName is None:
        return jsonify(code=-1, msg="请填写合作店铺名称～")
    if price is None:
        return jsonify(code=-1, msg="请求出错，请填写服务价格～")
    if payType not in [0,1,2,3]:
        return jsonify(code=-1, msg="请求出错，选择支付方式～")
    if payorder is None:
        return jsonify(code=-1, msg="请求出错，请填写支付交易号～")
    if startTime is None:
        return jsonify(code=-1, msg="请求出错，请填写服务起始日期～")
    if endTime is None:
        return jsonify(code=-1, msg="请求出错，请填写服务结束日期～")

    coop = UserCoop(phone=phone,name=name,wechat=wechat,shopName=shopName,coopName=coopName,
                    price=price,startTime=startTime,endTime=endTime,comment=comment,payType=payType,
                    payorder=payorder,aid=aid.id)

    try:
        db.session.add(coop)
        db.session.commit()
        return jsonify(code=0, msg="保存合作成功",data={
            "id":coop.id,
            "phone":coop.phone,
            "name":coop.name,
            "wechat":coop.wechat,
            "shopName":coop.shopName,
            "coopName": coop.coopName,
            "price": coop.price,
            "startTime": str(coop.startTime),
            "endTime": str(coop.endTime),
            "comment": coop.comment,
            "past":True if coop.endTime >= datetime.datetime.now().date() else False,
            "payType": coop.payType,
            "payorder":coop.payorder,
            "admin":coop.admin.name,
            "createtime": str(coop.createtime),
        })
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="保存合作失败，请刷新页面重试～")


# 获得合作

@app.route('/pdd/admin/usercoop', methods=["get"])
@admin_require
def admin_user_coop(aid):

    page = request.args.get('page', default=1, type=int)
    keyword = request.args.get("keyword", type=str)
    startTime = request.args.get("startTime", type=str)
    endTime = request.args.get("endTime", type=str)
    past = request.args.get("past", type=inputs.boolean)
    pageSize = request.args.get('pageSize', default=10, type=int)
    sql = list()
    if keyword:
        sql.append(
            or_(
                UserCoop.name.like(f"%{keyword}%"),
                UserCoop.phone.like(f"%{keyword}%"),
                UserCoop.coopName.like(f"%{keyword}%"),
                UserCoop.shopName.like(f"%{keyword}%")
            )
        )

    if not aid.job.initial:
        sql.append(UserCoop.aid==aid.id)

    if startTime and endTime:
        endTime = datetime.datetime.strptime(endTime, '%Y-%m-%d') + datetime.timedelta(days=1)
        sql.append(UserCoop.createtime.between(startTime, endTime))
    if past is not None:
        #true 合作中
        if past:
            sql.append(UserCoop.endTime >= datetime.datetime.now().date())
        else:
            sql.append(UserCoop.endTime < datetime.datetime.now().date())
    coop = UserCoop.query.filter(*sql).paginate(page, per_page=pageSize,error_out=False)

    data = [{
        "id":i.id,
        "phone": i.phone,
        "name": i.name,
        "wechat": i.wechat,
        "shopName": i.shopName,
        "coopName": i.coopName,
        "price": i.price,
        "startTime": str(i.startTime),
        "endTime": str(i.endTime),
        "comment": i.comment,
        "payType": i.payType,
        "payorder": i.payorder,
        "admin": i.admin.name if i.aid is not None else "暂无归属",
        "createtime":str(i.createtime),
        "past": True if i.endTime >= datetime.datetime.now().date() else False,
    } for i in coop.items]

    return jsonify(code=0, msg="获取成功～",data=data,page=coop.page,pages=coop.pages,total=coop.total)


# 编辑合作

@app.route('/pdd/admin/usercoop/edit', methods=["post"])
@admin_require
def admin_user_coop_edit(aid):

    id = request.form.get('id', type=int)
    phone = request.form.get("phone", type=int)
    name = request.form.get("name", type=str)
    wechat = request.form.get("wechat", type=str)
    shopName = request.form.get("shopName", type=str)
    coopName = request.form.get("coopName", type=str)
    price = request.form.get("price", type=float)
    payType = request.form.get("payType", type=int)
    payorder = request.form.get("payorder", type=str)
    startTime = request.form.get("startTime", type=str)
    endTime = request.form.get("endTime", type=str)
    comment = request.form.get("comment", type=str)
    sql = list()
    sql.append(UserCoop.id ==id)
    if not aid.job.initial:
        sql.append(UserCoop.aid==aid.id)
    if id is None:

        return jsonify(code=-1, msg="请求出错，请刷新重试～")

    coop =  UserCoop.query.filter(*sql).first()
    if not coop:
        return jsonify(code=-1,msg="请求出错，请刷新重试～")

    if phone:
        coop.phone=phone

    if name:
        coop.name=name

    if wechat:
        coop.wechat = wechat

    if shopName:
        coop.shopName = shopName

    if coopName:
        coop.coopName = coopName

    if price:
        coop.price = price

    if payType in [0,1,2,3]:
        coop.payType = payType

    if payorder:
        coop.payorder = payorder

    if startTime:
        coop.startTime = startTime

    if endTime:
        coop.endTime = endTime

    if comment:
        coop.comment = comment

    try:
        db.session.commit()
        return jsonify(code=0,msg="保存成功",data={
            "id":coop.id,
            "phone":coop.phone,
            "name":coop.name,
            "wechat":coop.wechat,
            "shopName":coop.shopName,
            "coopName": coop.coopName,
            "price": coop.price,
            "startTime": str(coop.startTime),
            "endTime": str(coop.endTime),
            "comment": coop.comment,
            "past":True if coop.endTime >= datetime.datetime.now().date() else False,
            "payType": coop.payType,
            "payorder":coop.payorder,
            "admin":coop.admin.name,
            "createtime": str(coop.createtime),
        })
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="保存失败")


# 删除合作
@app.route('/pdd/admin/usercoop/delete', methods=["post"])
@admin_require
def admin_user_coop_delete(aid):
    id = request.form.get('id', type=int)
    sql = list()
    sql.append(UserCoop.id ==id)

    if not aid.job.initial:
        sql.append(UserCoop.aid==aid.id)

    if id is None:
        return jsonify(code=-1, msg="请求出错，请刷新重试～")

    coop =  UserCoop.query.filter(*sql).first()
    if not coop:
        return jsonify(code=-1, msg="请求出错，请刷新重试～")

    try:
        db.session.delete(coop)
        db.session.commit()
        return jsonify(code=0,msg="删除成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="删除失败")

